package org.hry.netty.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        System.out.println("接受到请求信息: " + req.method() + " " + req.uri());

        // 处理GET请求
        if (HttpMethod.GET.equals(req.method())) {
            handleGetRequest(ctx, req);
        }
        // 处理POST请求
        else if (HttpMethod.POST.equals(req.method())) {
            handlePostRequest(ctx, req);
        }
    }

    private void handleGetRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        String responseContent = "这是一个Get请求";
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(responseContent, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private void handlePostRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 检查是否需要发送100 Continue响应
        if (HttpUtil.is100ContinueExpected(req)) {
            send100Continue(ctx);
        }

        // 获取请求体内容
        String body = req.content().toString(CharsetUtil.UTF_8);
        System.out.println("接收到请求体内容: " + body);

        // 根据Content-Type处理不同的请求体
        String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType != null) {
            if (contentType.contains("application/json")) {
                // 处理JSON数据
                handleJsonData(ctx, body);
            } else if (contentType.contains("multipart/form-data")) {
                // 处理表单数据
                handleFormData(ctx, body);
            } else {
                // 其他类型的Content-Type
                handleOtherData(ctx, body);
            }
        } else {
            // Content-Type头不存在
            handleNoContentType(ctx, body);
        }
    }

    private void handleJsonData(ChannelHandlerContext ctx, String body) {
        System.out.println("处理JSON数据: " + body);
        // 这里可以添加处理JSON数据的逻辑，例如使用JSON解析库
        String responseContent = "接收到JSON数据";
        sendResponse(ctx, responseContent);
    }

    private void handleFormData(ChannelHandlerContext ctx, String body) {
        System.out.println("处理表单数据: " + body);
        // 这里可以添加处理表单数据的逻辑，例如解析键值对
        String responseContent = "接收到表单数据";
        sendResponse(ctx, responseContent);
    }

    private void handleOtherData(ChannelHandlerContext ctx, String body) {
        System.out.println("处理其他类型的数据: " + body);
        String responseContent = "接收到其他类型的数据";
        sendResponse(ctx, responseContent);
    }

    private void handleNoContentType(ChannelHandlerContext ctx, String body) {
        System.out.println("Content-Type头不存在");
        String responseContent = "Content-Type头不存在";
        sendResponse(ctx, responseContent);
    }

    private void send100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.CONTINUE);
        ctx.writeAndFlush(response);
    }

    private void sendResponse(ChannelHandlerContext ctx, String responseContent) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(responseContent, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
